package com.lyn.serialport

import android.os.Bundle
import android.os.SystemClock
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.lyn.serialport.databinding.ActivityMainBinding
import java.util.Arrays

/**
 * @author longyn 2025/3/13
 * @version 1.0.0
 */
class MainActivity : AppCompatActivity() {

    private val TAG = "MainActivity"
    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        val serialPort = SerialPort()
        val fileDescriptor = serialPort.open("dev/ttyS3", 9600, 0)
        if (fileDescriptor!=null){
            Log.d(TAG,"打开成功")
        }else{
            Log.d(TAG,"打开失败")
        }
        //发送数据
        serialPort.getOutStream()?.write(byteArrayOf(0x00,0x00))

        //读取数据
        serialPort.getInputStream()?.let {
            Thread{
                while (true){
                    val available = it.available()
                    if (available<=0){
                        SystemClock.sleep(10)
                        continue
                    }
                    val data = ByteArray(available)
                    val read = it.read(data)
                    if (read>0){
                        Log.d(TAG,"读取成功:${data.contentToString()}")
                    }
                    SystemClock.sleep(10)
                }
            }.start()

        }
    }
}